package com.codejam.enums.demo.jackson;

import com.codejam.enums.demo.enums.IEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.util.CollectionUtils;

public class EnumJsonSerializer extends JsonSerializer<IEnum> {

    @Override
    public void serialize(IEnum anEnum, JsonGenerator jgen, SerializerProvider provider)
        throws IOException {
        if (Objects.isNull(anEnum)) {
            jgen.writeObject(null);
            jgen.writeFieldName(jgen.getOutputContext().getCurrentName()+"Desc");
            jgen.writeObject(null);
            return;
        }

        Class<? extends IEnum> aClass = anEnum.getClass();
        Field[] fields = aClass.getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields).filter(f -> !Modifier.isStatic(f.getModifiers())).collect(
            Collectors.toList());

        if (CollectionUtils.isEmpty(fieldList)) {
            jgen.writeObject(anEnum.getDesc());
        } else {
            jgen.writeStartObject();

            for (Field field : fieldList) {
                field.setAccessible(true);
                jgen.writeFieldName(field.getName());
                try {
                    jgen.writeObject(field.get(anEnum));
                } catch (IllegalAccessException e) {
                    throw new IOException(e);
                }
            }
            //增加返回字段 xxxEnumValue
            jgen.writeFieldName("enumValue");
            jgen.writeString(anEnum.toString());
            jgen.writeEndObject();
        }


    }

    @Override
    public Class handledType() {
        return IEnum.class;
    }
}